/**
 * 用户的状态管理
 */

// 定义数据的存储
const state = {
	// 用户信息(用于登录)
	userInfo: null,
	// keepalive数组,用于keepAlive组件
	keepAlive: [],
	// 当前激活的路由,用于左侧激活时
	activeRoute: null
}

// 获取数据(可以对数据进行改变,过滤)
// getters里面的方法,第一个接收的参数是局部状态对象,这个对象是从context里面取出来的
const getters = {
	getUserInfo: (state) => {
		return state.userInfo
	},
	// keepalive返回的是里面的route_name名字
	getKeepAliveComponentNames: (state) => {
		let componentNames = []
		state.keepAlive.forEach(item => {
			componentNames.push(item.route_name)
		})
		return componentNames
	},
	// 这是返回keepalive数组,数据里面是对象
	getKeepAlive: (state) => {
		return state.keepAlive
	},
	// 返回当前激活的路由
	getActiveRoute: (state) => {
		return state.activeRoute
	}
}

// 定义mutations,用于定义修改数据方法,只支持[同步]操作
// 定义mutations里面的方法第一个接受的参数也是局部状态对象
const mutations = {
	SET_USER_INFO: (state, userInfo) => {
		state.userInfo = userInfo
	},
	ADD_KEEP_ALIVE: (state, menu) => {
		state.keepAlive.push(menu)
		state.keepAlive = Array.from(new Set(state.keepAlive))
	},
	REMOVE_KEEP_ALIVE: (state, tag) => {
		let arr = state.keepAlive
		arr.splice(arr.findIndex(item => item === tag), 1)
	},
	REMOVE_ALL_KEEP_ALIVE: (state) => {
		state.keepAlive = []
	},
	SET_ACTIVE_ROUTE: (state, route) => {
		state.activeRoute = route
	}
}

// 定义actions,用户[异步]操作,用户接触的方法
// 对于actions,局部状态通过context.state暴露出来,这里是使用ES6语法将context对象解构
const actions = {
	setUserInfo: ({commit}, userInfo) => {
		commit('SET_USER_INFO', userInfo)
	},
	// 当点击左侧导航栏时添加keepAlive
	addKeepAlive({commit}, menu) {
		commit('ADD_KEEP_ALIVE', menu)
	},
	// 当点击标签移除时,移除这个keepAlive
	removeKeepAlive({commit}, tag) {
		commit('REMOVE_KEEP_ALIVE', tag)
	},
	removeAllKeepAlive({commit}) {
		commit('REMOVE_ALL_KEEP_ALIVE')
	},
	setActiveRoute({commit}, route) {
		commit('SET_ACTIVE_ROUTE', route)
	}
}

export default {
	namespaced: true,
	state,
	getters,
	mutations,
	actions
}

